﻿using Microsoft.AspNetCore.Authorization;

namespace PMRC.API.Authorization
{
    /// <summary>
	/// 自定义授权策略
	/// </summary>
    public class AuthorizationPolicyProvider : IAuthorizationPolicyProvider
    {
        /// <summary>
		/// 获取默认的授权策略
		/// </summary>
		/// <returns></returns>
        public async Task<AuthorizationPolicy> GetDefaultPolicyAsync()
        {
            return await Task.FromResult(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
        }

        /// <summary>
		/// 回退的授权策略
		/// </summary>
		/// <returns></returns>
        public async Task<AuthorizationPolicy?> GetFallbackPolicyAsync()
        {
            return await Task.FromResult<AuthorizationPolicy>(null);
        }

        /// <summary>
		/// 根据给定的策略名称获取授权策略
		/// </summary>
		/// <param name="policyName"></param>
		/// <returns></returns>
        public async Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
        {
            //参考地址
            //https://blog.csdn.net/mzl87/article/details/127906181
            //查询策略下的角色
            var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .AddRequirements(new AuthorizationRequirement(policyName))
                    .Build();
            return await Task.FromResult(policy);
        }
    }
}
